#ifndef CITYCODE_H
#define CITYCODE_H
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QMap>
#include <QObject>
class CityCode
{
private:
    static QMap<QString, QString> mCityMap;

    static void initCityMap()
    {
        //1.读取文件
        QString filePath = ":/cityCode.json";
        QFile file(filePath);
        file.open(QIODevice::ReadOnly | QIODevice::Text);
        QByteArray json = file.readAll();
        file.close();

        //2.解析，并写入到map
        QJsonParseError err;
        QJsonDocument doc = QJsonDocument::fromJson(json, &err);
        if (err.error != QJsonParseError::NoError) {
            return;
        }
        if (!doc.isArray()) {
            return;
        }
        QJsonArray cities = doc.array();
        for (int i = 0; i < cities.size(); i++) {
            QString cityName = cities[i].toObject().value("cityName").toString();
            QString cityCode = cities[i].toObject().value("cityCode").toString();
            if (cityCode.size() > 0) {
                mCityMap.insert(cityName, cityCode);
            }
        }
    }

public:
    static QString getCityCode(QString cityName)
    {
        if (mCityMap.isEmpty()) {
            initCityMap();
        }
        QMap<QString, QString>::iterator it = mCityMap.find(cityName);
        if (it == mCityMap.end()) {
            QString trimmedCityName = cityName.left(cityName.length() - 1);
            it = mCityMap.find(trimmedCityName);
        }
        if (it != mCityMap.end()) {
            return it.value();
        }
        return QString();
    }
};
QMap<QString, QString> CityCode::mCityMap = {};
#endif // CITYCODE_H
